<template>
    <n-tabs v-model:value="tabValue" justify-content="start" type="line">
        <n-tab-pane name="list" tab="文章列表">
           <div v-for="(blog,index) in blogListInfo" style="margin-bottom: 15px;">
              <n-card :title ="blog.title">
                   {{ blog.content }}
                   <template #footer>
                        <n-space align = "center">
                            <div>发布时间:{{ blog.create_time }}</div>
                            <n-button @click="toUpdate(blog)">修改</n-button>
                            <n-button @click="toDelete(blog)">删除</n-button>
                        </n-space>
                   </template>
              </n-card>
           </div>

           <!-- 添加页码 -->
           <n-space>
               <div @click="toPage(pageNum)"  v-for="pageNum in pageInfo.pageCount">
                <!-- 字符串拼装 -->
                    <div :style="'color:' + (pageNum == pageInfo.page ? 'red':'')">  {{ pageNum }} </div>
                  
               </div>
           </n-space>


        </n-tab-pane>
        <n-tab-pane name="add" tab="添加文章">
            <n-form>
                <n-form-item label="标题">
                    <n-input v-model:value="addArticle.title" placeholder="请输入标题"/>
                </n-form-item>
                <n-form-item label="分类">
                    <n-select v-model:value="addArticle.categoryId" :options="categortyOptions"/>
                </n-form-item>
                <n-form-item label="内容">
                    <rich-text-editor v-model="addArticle.content"></rich-text-editor>
                </n-form-item>
                <n-form-item label="">
                    <n-button @click="add">提交</n-button>
                </n-form-item>
            </n-form>
        </n-tab-pane>
        <n-tab-pane name="update" tab="修改">
            <n-form>
                <n-form-item label="标题">
                    <n-input v-model:value="updateArticle.title" placeholder="请输入标题"/>
                </n-form-item>
                <n-form-item label="分类">
                    <n-select v-model:value="updateArticle.categoryId" :options="categortyOptions"/>
                </n-form-item>
                <n-form-item label="内容">
                    <rich-text-editor v-model="updateArticle.content"></rich-text-editor>
                </n-form-item>
                <n-form-item label="">
                    <n-button @click="update">提交</n-button>
                </n-form-item>
            </n-form>
        </n-tab-pane>
    </n-tabs>
</template>

<script setup>
    import { AdminStore } from '../../stores/AdminStore'
    import { ref,reactive,inject ,onMounted } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import RichTextEditor from '../../components/RichTextEditor.vue'
    const router =  useRouter()
    const route = useRoute()

    const message = inject("message")
    const dialog = inject("dialog")
    const axios = inject("axios")


    const adminstore = AdminStore()

    // 文章添加响应对象
    const addArticle = reactive({
        categoryId:0,    // 分类id
        title:"",
        content:"",
    })

    // 定义修改响应对象
    const updateArticle = reactive({
        id:0,
        categoryId:0,    // 分类id
        title:"",
        content:"",
    })

    const categortyOptions = ref([])
    const blogListInfo = ref([])
    const tabValue = ref("list")

    const pageInfo = reactive({
        // 每页展示3条数据
        page:1,
        pageSize:3,
        // 初始化，默认页面最大数
        pageCount:0,
        // 数据最大值
        count:0,
    })


    onMounted(()=>{
        // 从服务端读取所有的博客列表数据
        loadBlogs()

        // 从服务端读取所有分类数据
        loadCategorys()

     
    })


    const loadBlogs = async () => {
        // let blogres = await axios.get("/blog/search")
        // 这里修改代码，用模板的方式传值,使用get方法,将页面和页面最大数据传到接口里
        let blogres = await axios.get(`/blog/search?page=${pageInfo.page}&pageSize=${pageInfo.pageSize}`)
        let temp_rows = blogres.data.data.rows
        
        for(let row of temp_rows){
            row.content += "..."
            // 转换时间戳数据
            let d = new Date(row.create_time)
            row.create_time = `${d.getFullYear()}年${d.getMonth()+1}月${d.getDate()}日${d.getHours()}时${d.getMinutes()}分${d.getSeconds()}秒`
        }

        blogListInfo.value = temp_rows
        pageInfo.count = blogres.data.data.count;
        // 获取页面总数
        pageInfo.pageCount = parseInt(pageInfo.count / pageInfo.pageSize) + (pageInfo.count % pageInfo.pageSize > 0 ? 1 : 0);
        console.log(blogres);
         
    }


    const loadCategorys = async () => {
        // 读取后端分类数据接口
        let res = await axios.get("/category/list")
        categortyOptions.value = res.data.rows.map((item)=>{
            return{
                label:item.name,
                value:item.id
            }
        })
        // console.log(categortyOptions.value)
     }

     // 博客提交 有问题
     const add = async () =>{
        // 这个提交功能有问题
        let res = await axios.post("/blog/_token/add",addArticle)
        if(res.data.code == 200){
            // 添加成功
            message.info(res.data.msg)
            // 添加成功后，页面内容清空
            addArticle.title = "",
            addArticle.content = "",
            addArticle.categoryId = 0
        }
        else{
            // 未添加成功
            message.error(res.data.msg)
        }

     }

     const toPage = async(pageNum) =>{
        pageInfo.page = pageNum
        loadBlogs()
     }

     const toUpdate = async (blog) =>{
        tabValue.value = "update"
        let res = await axios.get("/blog/detail?id="+blog.id)
        updateArticle.id = blog.id
        updateArticle.title = res.data.rows[0].title
        updateArticle.content = res.data.rows[0].content
        updateArticle.categoryId = res.data.rows[0].category_id

     }

     const update =  async () => {
        // 修改博客文章失败  检查原因都是因为请先登录，检测不到 token值
        let res = await axios.put("/blog/_token/update",updateArticle)
        if(res.data.code == 200){
       
            message.info(res.data.msg)
            loadBlogs()
            tabValue.value = "list"

        }
        else{
            // 未添加成功
            message.error(res.data.msg)
        }
     }

     const toDelete = async (blog) =>{
        let res = await axios.delete("/blog/_token/delete?id="+blog.id)
        if(res.data.code == 200){  
            message.info(res.data.msg)
            loadBlogs()
        }
        else{
            // 未添加成功
            message.error(res.data.msg)
        }
     }



</script>

<style lang="scss" scoped>

</style>